package com.lagou.controller;

import com.lagou.bean.UpLoadResult;
import com.lagou.service.FileUpLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/oss")
public class UploadController {
    @Autowired
    private FileUpLoadService fileUpLoadService;

    @PostMapping("/upload")
    public UpLoadResult upload(@RequestParam("file") MultipartFile multipartFile) {
        return fileUpLoadService.upload(multipartFile);
    }

    @GetMapping("/download")
    public void downloadFile(String fileUrl, HttpServletResponse response) throws IOException {
        byte[] bytes = fileUpLoadService.get(fileUrl);
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileUrl, "UTF-8"));
        response.setCharacterEncoding("UTF-8");
        ServletOutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();
            outputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @GetMapping("/delete")
    public String deleteFile(String fileUrl) {
        fileUpLoadService.deleteFile(fileUrl);
        return "delete success";
    }
}
